import requests
import time
from bs4 import BeautifulSoup
from openpyxl import load_workbook
import datetime
from email.mime.text import MIMEText
import smtplib

# 从xlsx文件中读取数据
def get_info():
    username = []
    password = []
    wb = load_workbook(filename='D:\\info.xlsx') 
    sheetnames = wb.get_sheet_names() 
    sheet = wb.get_sheet_by_name(sheetnames[0]) 
    row = wb[sheetnames[0]].max_row
    for rowNum in range(2,row+1):
        username.append(sheet.cell(row=rowNum,column=9).value) 
        password.append(sheet.cell(row=rowNum,column=10).value)
    sum = len(username)
    return username, password, sum

# 登录，为后续做准备
def login(s,headers,username,password):
    login_url = 'http://yiqing.ctgu.edu.cn/wx/index/loginSubmit.do'
    data = {
        'username':'',
        'password':'',
    }
    data['username'] = username
    data['password'] = password
    r = s.post(url = login_url,headers = headers,data = data )
    return r.text

# 获取要带有data的html
def get_student_info(s,headers):
    student_info_url = 'http://yiqing.ctgu.edu.cn/wx/health/toApply.do'
    r = s.get(url = student_info_url,headers = headers)
    # print(r.text)
    return r.text

# 解析html,获得data数据
def student_info_parse(html):
    bs = BeautifulSoup(html,'lxml')
    data = {
        'ttoken': bs.find(attrs={'name':'ttoken'})['value'],
        'province': bs.find(attrs={'name':'province'})['value'],
        'city': bs.find(attrs={'name':'city'})['value'],
        'district': bs.find(attrs={'name':'district'})['value'],
        'adcode': bs.find(attrs={'name':'adcode'})['value'],
        'longitude': bs.find(attrs={'name':'longitude'})['value'],
        'latitude': bs.find(attrs={'name':'latitude'})['value'],
        'sfqz': bs.find(attrs={'name':'sfqz'})['value'],
        'sfys': bs.find(attrs={'name':'sfys'})['value'],
        'sfzy': bs.find(attrs={'name':'sfzy'})['value'],
        'sfgl': bs.find(attrs={'name':'sfgl'})['value'],
        'status': bs.find(attrs={'name':'status'})['value'],
        'sfgr': bs.find(attrs={'name':'sfgr'})['value'],
        'szdz':bs.find(attrs={'name':'szdz'})['value'],
        'sjh': bs.find(attrs={'name':'sjh'})['value'],
        'lxrxm': bs.find(attrs={'name':'lxrxm'})['value'],
        'lxrsjh': bs.find(attrs={'name':'lxrsjh'})['value'],
        'sffr': '否',
        'sffy': '否',
        'sfgr': '否',
        'qzglsj': '',
        'qzgldd': '',
        'glyy': '',
        'mqzz': '',
        'sffx': '否',
        'qt':'',
    }
    return data

# 向服务器post数据
def sent_info(s,headers,data):
    sent_info_url = 'http://yiqing.ctgu.edu.cn/wx/health/saveApply.do'
    r = s.post(url = sent_info_url,headers = headers,data = data)
    # print(r.text)
    # print(r.status_code)

# 发邮件通知结果
def send_rusult(text):
    nowtime = datetime.datetime.now().strftime('%m-%d')
    msg_from=''#发送邮箱
    passwd='' #密码
    msg_to='' #目的邮箱
                                
    subject= '安全上报结果'   
    content= text+'\n'+nowtime
    msg = MIMEText(content)
    msg['Subject'] = subject
    msg['From'] = msg_from
    msg['To'] = msg_to

    s = smtplib.SMTP_SSL("smtp.163.com",994)
    s.login(msg_from, passwd)
    s.sendmail(msg_from, msg_to, msg.as_string())
    print ("发送结果成功")
    s.quit()

def main():
    username, password, sum = get_info()
    print('---------------------------')
    print('账号密码读取成功，共',sum,'人')
    print('---------------------------\n')
    finished = 0
    try:
        for i in range(sum):
            headers = {       
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.7 Safari/537.36'
            }
            s = requests.Session()
            state = login(s,headers,username[i],password[i])
            if state == 'success':
                print('用户',username[i],'登录成功')
            else:
                print('用户',username[i],'密码错误，登录失败\n')
                continue
            html = get_student_info(s,headers)
            try:
                data = student_info_parse(html)
                sent_info(s,headers,data)
                print('用户',username[i],'上报成功\n')
            except:
                print('用户',username[i],'今日已上报\n')
            finished += 1
            time.sleep(1)
    finally:
        text = '应报:'+str(sum)+'实报:'+str(finished)
        print(text)
        send_rusult(text)

if __name__ == "__main__":
    main()